package com.security.door.controller.areaManage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.security.door.core.wrapper.WrapMapper;
import com.security.door.core.wrapper.Wrapper;
import com.security.door.model.domain.crArea;
import com.security.door.model.domain.crAreaDevice;
import com.security.door.model.dto.crAreaDto;
import com.security.door.model.vo.crAreaTreeVo;
import com.security.door.service.IcrAreaDeviceService;
import com.security.door.service.IcrAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@Api(value = "WEB - crAreaController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class crAreaController {
    @Autowired
    HttpSession session;
    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    IcrAreaService icrAreaService;
    @Autowired
    IcrAreaDeviceService icrAreaDeviceService;

    @GetMapping("/area/queryListWithPage")
    @ApiOperation(value = "分页查询所有区域信息", notes = "分页查询所有区域信息")
    public Wrapper<PageInfo<crArea>> queryListWithPage() {
        crAreaDto entityDto = new crAreaDto();
        int pageIndex = httpServletRequest.getParameter("start") == null ? 0 : Integer.parseInt(httpServletRequest.getParameter("start"));
        int pageSize = httpServletRequest.getParameter("length") == null ? Integer.MAX_VALUE : Integer.parseInt(httpServletRequest.getParameter("length"));
        String searchStr = httpServletRequest.getParameter("search[value]");
        entityDto.setKeyWord(searchStr);
        PageHelper.startPage(pageIndex, pageSize);
        var list = icrAreaService.queryListWithPage(entityDto);
        return WrapMapper.ok(list);
    }

    @GetMapping("/area/queryListTree")
    @ApiOperation(value = "分页查询所有区域信息", notes = "分页查询所有区域信息")
    public Wrapper queryListTree() {
        crAreaDto entityDto = new crAreaDto();
        int pageIndex = httpServletRequest.getParameter("start") == null ? 0 : Integer.parseInt(httpServletRequest.getParameter("start"));
        int pageSize = httpServletRequest.getParameter("length") == null ? Integer.MAX_VALUE : Integer.parseInt(httpServletRequest.getParameter("length"));
        String searchStr = httpServletRequest.getParameter("search[value]");
        entityDto.setKeyWord(searchStr);
        PageHelper.startPage(pageIndex, pageSize);
        var list = icrAreaService.queryListWithPage(entityDto);
        return WrapMapper.ok(this.getTree(list.getList(), null));
    }

    private List<crAreaTreeVo> getTree(List<crArea> list, String parentId) {
        List<crArea> parentNode;
        if (null == parentId)
            parentNode = list.stream().filter(x -> x.getParentcode() == parentId).collect(Collectors.toList());
        else {
            list.removeIf(x -> x.getParentcode() == null);
            parentNode = list.stream().filter(x -> x.getParentcode().equals(parentId)).collect(Collectors.toList());
        }
        List<crAreaTreeVo> listVo = new LinkedList<>();
        parentNode.forEach(x -> {
            crAreaTreeVo temp = new crAreaTreeVo();
            temp.setGuid(x.getGuid());
            temp.setId(x.getAreacode());
            temp.setText(x.getAreaname());
            temp.setPid(parentId);
            List<crAreaTreeVo> tempList = getTree(list, x.getAreacode());
            if (tempList.size() > 0)
                temp.setNodes(tempList);
            listVo.add(temp);
        });
        return listVo;
    }

    @GetMapping("/area/selectByAreaCode/{areaCode}")
    @ApiOperation(value = "查询区域信息", notes = "查询区域信息")
    public Wrapper selectByAreaCode(@PathVariable("areaCode") String areaCode) {
        var entity = icrAreaService.selectByAreaCode(areaCode);
        return WrapMapper.ok(entity);
    }

    @PostMapping("/area/add")
    @ApiOperation(value = "新增区域信息", notes = "新增区域信息")
    public Wrapper add(@RequestBody crArea entity) {
        if ("".equals(entity.getGuid()) || entity.getGuid() == null) {
            entity.setGuid(UUID.randomUUID().toString());
            entity.setCreatetime(new Date());
            icrAreaService.save(entity);
        } else {
            icrAreaService.update(entity);
        }
        return WrapMapper.ok("操作成功");
    }

    @GetMapping("/area/del/{guid}")
    @ApiOperation(value = "删除区域信息", notes = "删除区域信息")
    public Wrapper deleteByKey(@PathVariable("guid") String guid) {
        icrAreaService.deleteByKey(guid);
        return WrapMapper.ok("操作成功");
    }

    @PostMapping("/area/pull")
    @ApiOperation(value = "从主机同步区域", notes = "从主机同步区域")
    public Wrapper pull(@RequestBody crAreaDto entityDto) {
        var areaTemp = icrAreaService.selectByAreaCode(entityDto.getAreacode());
        if (null == areaTemp) {
            areaTemp = new crArea();
            areaTemp.setGuid(UUID.randomUUID().toString());
            areaTemp.setAreadevnum(entityDto.getAreadevnum());
            areaTemp.setAreacode(entityDto.getAreacode());
            areaTemp.setAreatype(entityDto.getAreatype());
            areaTemp.setAreaname(entityDto.getAreaname());
            areaTemp.setCreatetime(new Date());
            icrAreaService.save(areaTemp);
        } else {
            areaTemp.setAreadevnum(entityDto.getAreadevnum());
            areaTemp.setAreacode(entityDto.getAreacode());
            areaTemp.setAreatype(entityDto.getAreatype());
            areaTemp.setAreaname(entityDto.getAreaname());
            areaTemp.setCreatetime(new Date());
            icrAreaService.update(areaTemp);
        }
        //保存设备-区域关系
        crAreaDevice m_crAreaDevice = new crAreaDevice();
        m_crAreaDevice.setAreacode(entityDto.getAreacode());
        m_crAreaDevice.setDevicecode(entityDto.getDevicecode());
        if (!icrAreaDeviceService.hasExists(m_crAreaDevice)) {
            m_crAreaDevice.setGuid(UUID.randomUUID().toString());
            m_crAreaDevice.setCreatetime(new Date());
            icrAreaDeviceService.save(m_crAreaDevice);
        }
        return WrapMapper.ok("操作成功");
    }
}
